﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Repo7.BusinessLogic.Utils;
using System.Net;

namespace Repo7.BusinessLogic.Network.Cluster
{
    /// <summary>
    /// Repository Cluster Manager
    /// </summary>
    public class RepoClusterManager
    {
        #region Public Properties
        
        /// <summary>
        /// Peer List
        /// </summary>
        public IList<RepoPeerInfo> Peers { get; private set; }

        /// <summary>
        /// Information about the local Node
        /// </summary>
        public RepoLocalInfo LocalInformation { get; private set; }

        #endregion

        #region Constructor
        
        /// <summary>
        /// Constructor
        /// </summary>
        public RepoClusterManager()
        {
            Peers = new List<RepoPeerInfo>();
            LocalInformation = null;
        }

        #endregion

        #region Public Methods

        /// <summary>
        /// Initialize the Peer List
        /// </summary>
        public void InitPeerList()
        {
            //Get Peers Info
            Peers = CommonUtils.GetXmlConfiguredRepositoryPeers();
            //Get local repository settings
            LocalInformation = CommonUtils.GetXmlLocalRepositoryConfiguration();
        }

        /// <summary>
        /// Get Peer Info by name
        /// </summary>
        /// <param name="name">Peer Name</param>
        /// <returns></returns>
        public RepoPeerInfo GetPeerInfoByName(string name)
        {
            if (string.IsNullOrEmpty(name))
            {
                return null;
            }

            return Peers.FirstOrDefault(p => p.Name.Equals(name));
        }

        /// <summary>
        /// Get Peer Info By Command End Point IP Address
        /// </summary>
        /// <param name="ipAddress"></param>
        /// <returns></returns>
        public RepoPeerInfo GetPeerInfoByCommandIp(IPAddress ipAddress)
        {
            if (ipAddress == null)
            {
                return null;
            }

            return Peers.FirstOrDefault(p => p.CommandEndPont.Address.Equals(ipAddress));
        }

        /// <summary>
        /// Get Peer Info By Command End Point IP Address
        /// </summary>
        /// <param name="ipAddress"></param>
        /// <returns></returns>
        public RepoPeerInfo GetPeerInfoByFileTransferIp(IPAddress ipAddress)
        {
            if (ipAddress == null)
            {
                return null;
            }

            return Peers.FirstOrDefault(p => p.FileTransferEndPoint.Address.Equals(ipAddress));
        }

        #endregion
    }
}
